<!DOCTYPE html>
<html>
    <head>
        <title>Arcadia Map Editor</title>
        <link rel='stylesheet' href='css/main.css' />
        <script src='../../../js/lib/jquery-2.0.3.min.js'></script>
        <script>
            var width = 100;
            var height = 100;
            
            var sprites = new Object();
            var terrain = new Object();
            var invTerrain = new Object();
            
            var spriteCount = 0;
            
            var modifiers = new Object();
            modifiers.ctrl = false;
            modifiers.alt = false;
            modifiers.shift = false;
            modifiers.none = function() { return !(modifiers.ctrl || modifiers.alt || modifiers.shift); };
            
            $(document).ready(function() {
                // Create event handlers
                $(document).on('keydown', keyDown);
                $(document).on('keyup', keyUp);
                $(window).resize(resizeScreen);
                //document.oncontextmenu = function() {return false;};
                
                // Set default element states
                resizeScreen();
                $('.container').toggle();
                loadSpritesList();
            });
            
            function populateMapTable() {
                var table = $('.workwindow table tbody');
                $('.workwindow table').width(width * 66);
                for (var y = 0; y < height; y++) {
                    var row = $(document.createElement('tr'));
                    for (var x = 0; x < width; x++) {
                        // Default background
                        var defBg = 22;
                        row.append($(document.createElement('td'))
                            .addClass('mapcell')
                            .addClass('unselectable')
                            .on('mousedown', clickCell)
                            .attr({
                                x: x,
                                y: y,
                                collision: 0,
                                background: 0,
                                foreground: 0
                            })
                            .css({
                                "background-size": "64px 64px",
                                "background-repeat": "no-repeat",
                                "background-image": "url('../../../img/" + sprites[terrain[defBg]].source + "')"
                            })
                            .append($(document.createElement('img'))
                                .addClass('unselectable')
                                .css({
                                    opacity: 1
                                })
                            )
                            .append($(document.createElement('img'))
                                .addClass('unselectable')
                                .attr({
                                    src: 'img/circle-with-slash.png'
                                })
                            )
                            .attr('background', defBg)
                        );
                    }
                    table.append(row);
                }
            }
            
            function loadSpritesList() {
                var spriteUrl = "../../../sprites/_spriteList.json";
                var terrainUrl = "../../../maps/terrain.json";
                
                //console.log("Loading " + spriteUrl);
                $.getJSON(spriteUrl, function(data) {
                    loadSprites(data.sprites);
                }).fail(function(value) {
                    //console.log("1");
                }(spriteUrl));
                
                //console.log("Loading " + terrainUrl);
                $.getJSON(terrainUrl, function(data) {
                    terrain = data;
                    $.each(terrain, function(key, value) {
                        invTerrain[value] = key;
                    });
                }).fail(function(value) {
                    console.log("3");
                }(spriteUrl));
            }
            
            function loadSprites(spriteList) {
                $.each(spriteList, function(index, value) {
                    //console.log("Loading " + value);
                    $.getJSON('../../../' + value, function(data) {
                        sprites[data.id] = data;
                        spriteCount++;
                        if (invTerrain[data.id]) {
                            $('#terrainpalette option').each(function(index) {
                                if (index > 0 && data.id.toLowerCase() < $(this).text().toLowerCase()) {
                                    $(document.createElement('option'))
                                        .attr('value', data.id)
                                        .text(data.id)
                                        .insertBefore($(this));
                                    return false;
                                } else if ($('#terrainpalette option').size() - 1 == index) {
                                    $('#terrainpalette').append(
                                        $(document.createElement('option'))
                                            .attr('value', data.id)
                                            .text(data.id)
                                    );
                                }
                            });
                        }
                        if (spriteCount == spriteList.length) {
                            populateMapTable();
                        }
                    }).fail(function(value) {
                        //console.log("2");
                    }(value));
                });
            }
            
            function keyDown(e) {
                setModifier(e, true);
            }
            
            function keyUp(e) {
                setModifier(e, false);
            }
            
            function setModifier(e, value) {
                switch (e.which) {
                    case 16:
                        modifiers.shift = value;
                        break;
                    case 17:
                        modifiers.ctrl = value;
                        break;
                    case 18:
                        modifiers.alt = value;
                        break
                    default:
                        return false;
                }
                return true;
            }
            
            function clickCell(e) {
                if (e.which == 1) {
                    if (invTerrain[$('#terrainpalette').val()] == 0) {
                        src = "";
                    } else {
                        src = "../../../img/" + sprites[$('#terrainpalette').val()].source;
                    }
                    if (modifiers.none()) {
                        if ($('input[name=fgbg]:checked').val() == 'fg') {
                            // "Paint" Foreground
                            $('img', $(this)).first().attr('src', src);
                            $('img', $(this)).first().toggle(true);
                             $(this).attr('foreground', invTerrain[$('#terrainpalette').val()]);
                        }
                        else {
                            // "Paint" Background
                            $(this).css({
                                "background-image": "url('" + src + "')",
                            });
                            $(this).attr('background', invTerrain[$('#terrainpalette').val()]);
                        }
                    } else if (modifiers.shift) {
                        // Clear square
                        $('img', $(this)).last().toggle();
                        $(this).attr('collision', 1 - ($(this).attr('collision')));
                    } else if (modifiers.alt) {
                        // Toggle collision
                        $('img', $(this)).hide();
                        $(this).attr('collision', 0);
                        $(this).css({
                            "background-image": ""
                        });
                    } else if (modifiers.ctrl) {
                        // "Eyedropper" function
                        $('#terrainpalette').val(terrain[$(this).attr('background')]).prop('selected', true);
                    }
                }
                if ($('input[name=autoJSON]').prop('checked')) createJSON();
            }
            
            function resizeScreen() {
                var sWidth = $(window).width();
                var sHeight = $(window).height();
                $('.bottompanel').css({
                    width: (sWidth - 250) + "px"
                });
                $('.bottompanel textarea').css({
                    width: (sWidth - 255) + "px"
                });
                $('.workwindow').css({
                    width: (sWidth - 250) + "px",
                    height: (sHeight - 200) + "px"
                });
            }
            
            function defValue(value, def) {
                return value ? value : def;
            }
            
            function createJSON() {
                var theMap = new Object();
                theMap.id = 'editor_test';
                theMap.width = width;
                theMap.height = height;
                theMap.collisions = new Array(height * width);
                theMap.background = new Array(height * width);
                theMap.foreground = new Array(height * width);
                theMap.entities = [];
                
                $.each($('.maptable td'), function(key, val) {
                    var idx = parseInt($(val).attr('y') * width) + parseInt($(val).attr('x'));
                    theMap.collisions[idx] = defValue(parseInt($(val).attr('collision')), 0);
                    theMap.background[idx] = defValue(parseInt($(val).attr('background')), 0);
                    theMap.foreground[idx] = defValue(parseInt($(val).attr('foreground')), 0);
                });
                
                theMap.entities.push({
                    sprite: "player_boy2",
                    x: 5,
                    y: 5,
                    facing: 1,
                    behavior: {
                        type: "wander",
                        radius: 1
                    }
                });
                
                $('.bottompanel textarea').text(JSON.stringify(theMap, null, 2));
            }
        </script>
    </head>
    
    <body>
        <div class='container' style='display:none'>
            <div class='workwindow'>
                <table class='maptable'>
                    <tbody></tbody>
                </table>
            </div>
            <div class='leftpanel'>
                <div class='terrainpalette'>
                    <select id='terrainpalette'>
                        <option value="blank">blank</option>
                    </select><br />
                    <input type='radio' name='fgbg' value='bg' checked='checked'>Background<br />
                    <input type='radio' name='fgbg' value='fg'>Foreground<br />
                    <br />
                    <input type='checkbox' name='autoJSON' value='yes'>Auto-generate map?<br />
                </div>
            </div>
            <div class='bottompanel'>
                <textarea placeholder="Map data will appear here."></textarea>
            </div>
        </div>
        <noscript>This editor requires javascript.</noscript>
    </body>
</html>